package com.ql.gamelogm.controller;


import com.alibaba.fastjson.JSON;
import com.ql.gamelogm.entities.Log;
import com.ql.gamelogm.entities.Manager;
import com.ql.gamelogm.entities.RedisCache;
import com.ql.gamelogm.entities.Right;
import com.ql.gamelogm.service.LogService;
import com.ql.gamelogm.service.MailService;
import com.ql.gamelogm.service.ManagerService;
import com.ql.gamelogm.utils.IpUnit;
import com.ql.gamelogm.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
public class ManagerController {
    String ipAddr = IpUnit.getIpAddr();
    @Autowired
    private ManagerService managerService;
    @Autowired
    private LogService logService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private MailService mailService;
    //登录
    @RequestMapping(value = "/login")
    @ResponseBody
    public ModelAndView login() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("showipaddr", ipAddr);
        modelAndView.setViewName("LoginManager");
        return modelAndView;
    }

    //登录成功转到index响应
    @RequestMapping(value = "/index")
    @ResponseBody
    public ModelAndView actlogin( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,HttpSession httpSession) {
        ModelAndView modelAndView = new ModelAndView();
        Date date=new Date();
        date.setTime(System.currentTimeMillis());
        String managerid = httpServletRequest.getParameter("Managerid");
        String password = httpServletRequest.getParameter("Password");
        String getmanagerid = "";
        String getpassword = "";
        try {
            List<Manager> list = managerService.findManagerByID(managerid);
            //list判空，否则会抛出indexoutofbounds异常
            if (null != list && list.size() != 0) {
                getmanagerid = list.get(0).getId();
                getpassword = list.get(0).getPassword();
                if (!(password.equals(getpassword))) {
                    modelAndView.addObject("errorpassmes", "密码错误！");
                    modelAndView.setViewName("LoginManager");
                    httpSession.setAttribute("managerid",managerid);
                } else {
                    List<Right> rightList=managerService.findRightById(managerid);
                    httpSession.setAttribute("mr",rightList.get(0).getIsMailEdit());
                    httpSession.setAttribute("lr",rightList.get(0).getIsLogEdit());
                    httpSession.setAttribute("sr",rightList.get(0).getIsRightEdit());
                    httpSession.setAttribute("pr",rightList.get(0).getIsPersRightEdit());
                    httpSession.setAttribute("cr",rightList.get(0).getIsCalendarEdit());
                    modelAndView.setViewName("index");
                    httpSession.setAttribute("id",managerid);
                    //存登录记录
                    Log log=new Log();
                    log.setDate(date);
                    log.setOperator(managerid);
                    log.setOperation("登录");
                    log.setIpaddr(ipAddr);
                    logService.savelog(log);
                }
            } else {
                modelAndView.addObject("erroridmes", "用户不存在！");
                httpSession.removeAttribute("managerid");
                modelAndView.setViewName("LoginManager");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }

    /*查找用户*/
    @GetMapping(value = "/findManger")
    public String findManagers(Model model,HttpSession httpSession){
        String id = (String) httpSession.getAttribute("id");
        List<Manager> managerList=managerService.findAllManager();
        Manager manager=new Manager();
        for(int  i=0;i<managerList.size();i++){
            if((managerList.get(i).getId()).equalsIgnoreCase(id)){
                manager=managerList.get(i);
            }
        }
        //存登录记录
        Date date=new Date();
        date.setTime(System.currentTimeMillis());
        Log log=new Log();
        log.setDate(date);
        log.setOperator(id);
        log.setOperation("个人信息查询");
        log.setIpaddr(ipAddr);
        logService.savelog(log);
        model.addAttribute("manager",manager);
        return "UserPro";
    }
    /*人员管理*/
    @GetMapping(value = "/PersRightPre")
    public String findAllManagerList(Model model,@RequestParam(value = "pageNum", defaultValue = "0")int PageNum,@RequestParam(value = "pageSize",defaultValue = "8")int
    PageSize){
        Page<Manager>  allManagerList=managerService.getManager(PageNum,PageSize);
        model.addAttribute("allManagerList", allManagerList);
        return  "PersRight";
    }
    /*权限管理*/
    @GetMapping(value = "/SysRightPre")
    public String findAllRightList(Model model,@RequestParam(value = "pageNum", defaultValue = "0")int PageNum,@RequestParam(value = "pageSize",defaultValue = "8")int
            PageSize){
        Page<Right>  allRightsList=managerService.getRights(PageNum,PageSize);
        model.addAttribute("allRightsList", allRightsList);
        return  "SysRight";
    }
    //添加用户
    @RequestMapping(value = "/addManager")
    public String addManager(HttpServletRequest httpServletRequest ,HttpSession httpSession){

        String name=httpServletRequest.getParameter("MName1");
        String type=httpServletRequest.getParameter("MType1");
        String realName=httpServletRequest.getParameter("MRName1");
        String sex=httpServletRequest.getParameter("MSex1");
        String age=httpServletRequest.getParameter("MAge1");
        String addr=httpServletRequest.getParameter("MAddr1");
        String email=httpServletRequest.getParameter("MEmail1");
        String password="gly123456";
        int cage=Integer.parseInt(age);
        Manager manager=new Manager(name,type,realName,sex,cage,password,addr,email);
        boolean iao = managerService.addManager(manager);
        if(iao){
            Right right=new Right();
            right.setId(name);
            right.setManagerType(type);
            right.setIsMailEdit(0);
            right.setIsLogEdit(0);
            right.setIsRightEdit(0);
            right.setIsPersRightEdit(0);
            right.setIsCalendarEdit(0);
            managerService.addRight(right);
            //存添加用户操作记录
            String id=(String)httpSession.getAttribute("id");
            Date date=new Date();
            date.setTime(System.currentTimeMillis());
            String ipaddr= IpUnit.getIpAddr();
            Log log=new Log();
            log.setDate(date);
            log.setOperator(id);
            log.setOperation("添加用户");
            log.setIpaddr(ipaddr);
            logService.savelog(log);
            httpSession.setAttribute("isaddok",iao);
        }
        return "redirect:/PersRightPre";
    }
    //修改用户
    @RequestMapping(value = "/updateManager")
    public String updateManager(@RequestParam(value = "MName2")String MName2, HttpServletRequest httpServletRequest,HttpSession httpSession){


        String realName=httpServletRequest.getParameter("MRName2");
        String sex=httpServletRequest.getParameter("MSex2");
        String age=httpServletRequest.getParameter("MAge2");
        String addr=httpServletRequest.getParameter("MAddr2");
        String email=httpServletRequest.getParameter("MEmail2");
        Manager manager=new Manager();
        manager.setName(realName);
        manager.setSex(sex);
        manager.setAge(Integer.parseInt(age));
        manager.setLocation(addr);
        manager.setEmail(email);
        boolean iuo = managerService.updateManager(manager,MName2);
        if(iuo){
            //存修改用户操作记录
            String mid1=(String)httpSession.getAttribute("id");
            Date date=new Date();
            date.setTime(System.currentTimeMillis());
            String ipaddr= IpUnit.getIpAddr();
            Log log=new Log();
            log.setDate(date);
            log.setOperator(mid1);
            log.setOperation("修改用户");
            log.setIpaddr(ipaddr);
            logService.savelog(log);
            httpSession.setAttribute("isudok",iuo);
        }
        return "redirect:/PersRightPre";
    }

    //删除用户
    @RequestMapping(value = "/deleteManager")
    public String deleteManager(@RequestParam(value = "MName3")String MName3,HttpSession httpSession){
        boolean ido = managerService.deleteManager(MName3);
        managerService.deleteRightById(MName3);
        if(ido){
            //存删除用户操作记录
            String mid2=(String)httpSession.getAttribute("id");
            Date date=new Date();
            date.setTime(System.currentTimeMillis());
            String ipaddr= IpUnit.getIpAddr();
            Log log=new Log();
            log.setDate(date);
            log.setOperator(mid2);
            log.setOperation("删除用户");
            log.setIpaddr(ipaddr);
            logService.savelog(log);
            httpSession.setAttribute("isdelok",ido);
        }
        return "redirect:/PersRightPre";
    }
    //ajax用户名验证
    @RequestMapping("/checkManagerId")
    @ResponseBody
    public Map checkManagerId(HttpServletRequest request){
        String id=request.getParameter("name");
        boolean result=false;
        List<Manager> managerRedis = managerService.findAllManager();
        for(int i=0;i<managerRedis.size();i++){
            if(managerRedis.get(i).getId().equals(id)){
                result=true;
            }
        }
        Map map = new HashMap();
        map.put("res", result);
        return map;
    }
    //ajax邮箱验证
    @RequestMapping("/checkManagerEmail")
    @ResponseBody
    public Map checkManagerEmail(HttpServletRequest request){
        String email=request.getParameter("email");
        boolean result=false;
        List<Manager> managerRedis =managerService.findAllManager();
        for(int i=0;i<managerRedis.size();i++){
            if(managerRedis.get(i).getEmail().equals(email)){
                result=true;
            }
        }
        Map map = new HashMap();
        map.put("res", result);
        return map;
    }


    //修改用户
    @RequestMapping(value = "/updatePassword")
    public String updatePwd(@RequestParam(value = "mid")String mid,HttpServletRequest httpServletRequest,HttpSession httpSession){
        String pwd=httpServletRequest.getParameter("Mpass1");
        boolean ido = managerService.updatePwd(pwd,mid);
        if(ido){
            //存删除用户操作记录
            String midcp=(String)httpSession.getAttribute("id");
            Date date=new Date();
            date.setTime(System.currentTimeMillis());
            String ipaddr= IpUnit.getIpAddr();
            Log log=new Log();
            log.setDate(date);
            log.setOperator(midcp);
            log.setOperation("修改密码");
            log.setIpaddr(ipaddr);
            logService.savelog(log);
        }
        return "redirect:/findManger";
    }

    @RequestMapping("/sendCheckCode")
    @ResponseBody
    public Map SendCheckCode(HttpServletRequest request,HttpSession httpSession){
        httpSession.removeAttribute("code");
        String mailto=request.getParameter("email");
        List<Manager> managerList=managerService.findAllManager();
        String id="";
        if(managerList.get(0).getEmail().equals(mailto)){
            id=managerList.get(0).getId();
        }
        String email_subject="邮箱验证码";
        String base = "0123456789ABCDEFGabcdefg";
        int size = base.length();
        Random r = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i=1;i<=4;i++){
            //产生0到size-1的随机值
            int index = r.nextInt(size);
            //在base字符串中获取下标为index的字符
            char c = base.charAt(index);
            //将c放入到StringBuffer中去
            sb.append(c);
        }
        String message="管理员:"+id+",您的邮箱验证码为："+sb.toString();
        boolean isSendMailOky=mailService.SendMail(mailto,email_subject,message);
        if(isSendMailOky==true){
            Map map = new HashMap();
            map.put("send", sb.toString());
            httpSession.setAttribute("code",sb.toString());
            return map;
        }
        Map map = new HashMap();
        map.put("send", "no");
        return map;
    }
    @RequestMapping("/checkEmail")
    @ResponseBody
    public Map checkEmail(HttpServletRequest request){
        String email=request.getParameter("email");
        boolean res=false;
        List<Manager> managerRedis = managerService.findAllManager();
        for(int i=0;i<managerRedis.size();i++){
            if(managerRedis.get(i).getEmail().equals(email)){
                res=true;
            }
        }
        Map map = new HashMap();
        map.put("res", res);
        return map;
    }
    //删除用户
    @PostMapping(value = "/resetPassword")
    public String changePassword(HttpServletRequest httpServletRequest,HttpSession httpSession){
        String email=httpServletRequest.getParameter("email");
        httpSession.setAttribute("mail111",email);
        return "changePwd";
    }

    @PostMapping(value = "/returnLogin")
    public String returntologin(HttpServletRequest httpServletRequest,HttpSession httpSession){
        String email=(String)httpSession.getAttribute("mail111");
        String repass=httpServletRequest.getParameter("nrpwd");
        System.out.println(email+","+repass);
        boolean ido = managerService.updatenPwd(repass,email);
        return "redirect:/login";
    }


    //删除用户
    @RequestMapping(value = "/updateRight")
    public String updateRight(@RequestParam(value = "Name")String Name,HttpServletRequest httpServletRequest,HttpSession httpSession){
        String mailright=httpServletRequest.getParameter("mailRight");
        String logright=httpServletRequest.getParameter("logRight");
        String sysright=httpServletRequest.getParameter("sysRight");
        String persright=httpServletRequest.getParameter("persRight");
        String calright=httpServletRequest.getParameter("calRight");
        Right right=new Right();
        right.setIsMailEdit(Integer.parseInt(mailright));
        right.setIsLogEdit(Integer.parseInt(logright));
        right.setIsRightEdit(Integer.parseInt(sysright));
        right.setIsPersRightEdit(Integer.parseInt(persright));
        right.setIsCalendarEdit(Integer.parseInt(calright));
        boolean iur = managerService.updateRight(right,Name);
        if(iur){
            //存删除用户操作记录
            String midcp=(String)httpSession.getAttribute("id");
            Date date=new Date();
            date.setTime(System.currentTimeMillis());
            String ipaddr= IpUnit.getIpAddr();
            Log log=new Log();
            log.setDate(date);
            log.setOperator(midcp);
            log.setOperation("修改用户权限");
            log.setIpaddr(ipaddr);
            logService.savelog(log);
            httpSession.setAttribute("isudrok",iur);
        }
        return "redirect:/SysRightPre";
    }
}
